package com.kara.dao.impl;

import java.io.Serializable;

import java.util.HashMap;
import java.util.List;

import org.appfuse.dao.hibernate.GenericDaoHibernate;
import org.appfuse.model.User;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kara.dao.ClazzDao;
import com.kara.entity.SchoolYear;
import com.kara.entity.Trinn;
import com.kara.entity.Clazz;


@Repository("clazzDao")
public class ClazzDaoImpl extends GenericDaoHibernate<Clazz, Serializable> implements ClazzDao {

	@Autowired
	SessionFactory sessionFactory;
	
	public ClazzDaoImpl () {
		super(Clazz.class);
	}
	
	public ClazzDaoImpl(Class<Clazz> persistentClass, Serializable serializable) {
		super(persistentClass);
	}

	public List<User> getTeachers() {
		
		List <User> teachers =  getTeachers();
		User mainTeacher = getMainTeacher();
		
		if (teachers.contains(mainTeacher)){
			throw new IllegalStateException("Main teacher is included with other teachers., main teacherUserName:<"+mainTeacher.toString()+">");
		}
		return teachers;
	}

	public User getMainTeacher() {
		
		return getMainTeacher();
	}

	public Clazz saveClazz(Clazz clazz) {
		
		
		return save(clazz);
	}

	@SuppressWarnings("unchecked")
	public List<Clazz> getClazz(Trinn trinn) {
		
		String squery = " from Clazz c where c.trinn = :trinn";
		Query query = getQuery(squery);
		query.setString("trinn", trinn.toString());
		return query.list();

	}
	@SuppressWarnings("unchecked")
	public List<Clazz> getClazz(SchoolYear schoolYear) {
		
		String query = " from Clazz c where c.schoolYear.id = :id";
		
		Query createQuery = getQuery(query);
		createQuery.setLong("id", schoolYear.getId());
		
		List<Clazz> findByNamedQuery = createQuery.list();
		
		return findByNamedQuery; 
	}

	private Query getQuery(String query) {
		Query createQuery = getSessionFactory().getCurrentSession().createQuery(query);
		return createQuery;
	}	
}
